//和用户相关的状态管理
import { createSlice } from "@reduxjs/toolkit";
import { setToken as _setToken, getToken, removeToken } from "@/utils";
import { loginAPI,getProfileAPI } from "@/apis/user";
const userStore = createSlice({
  name: "user",
  initialState: {
    // token: localStorage.getItem("token_key") || " ",//token的持久化

    token: getToken() || " ",
    userInfo: {},
  },
  //同步修改方法
  reducers: {
    setToken(state, action) {
      state.token = action.payload;
      //存数据在reducers
      //localstore存一份
      // localStorage.setItem("token_key", action.payload);
      _setToken(action.payload);
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    clearUserInfo(state,action){
      state.token=''
      state.userInfo={}
      removeToken()
    }
  },
});
//解构出函数
const { setToken, setUserInfo,clearUserInfo } = userStore.actions;
//获取reducer 函数
const userReducer = userStore.reducer;
//表单里收集到的数据
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    //1.发送异步请求封装
    const res = await loginAPI(loginForm);
    //2.提交同步action进入token的存入
    dispatch(setToken(res.data.token));
  };
};
//获取个人信息的异步信息的接口
const fetchUserInfo = () => {
  return async (dispatch) => {
    //1.发送异步请求封装
   const res= await getProfileAPI()
   dispatch(setUserInfo(res.data))
  };
};
//导出
export { fetchLogin, setToken, fetchUserInfo,clearUserInfo };
export default userReducer;
